package io.mvvm.netty.ws;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @program: Netty
 * @description: WebSocketServer
 * @author: 潘
 * @create: 2021-04-29 09:24
 **/
public class WebSocketServer {

    private final static Logger logger = LoggerFactory.getLogger(WebSocketServer.class);

    public static void main(String[] args) throws InterruptedException {

        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try {

            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap
                    // 设置两个线程组
                    .group(bossGroup, workGroup)
                    // 设置服务端的通道实现
                    .channel(NioServerSocketChannel.class)
                    // 设置线程队列得到连接个数
                    .option(ChannelOption.SO_BACKLOG, 128)
                    // 设置保持活动连接状态
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    // 设置 workGroup 的 EventLoop 对应的通道设置处理器
                    .childHandler(new ChannelInitializer<SocketChannel>() { // 创建一个通道初始化对象
                        // 给 pipeline 设置处理器
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            // Http协议编解码器
                            ch.pipeline().addLast(new HttpServerCodec());
                            // 以块方式写,对大数据流的支持，例如文件传输
                            ch.pipeline().addLast(new ChunkedWriteHandler());
                            // 将多个数据段聚合起来，如果发送大文本数据避免请求多次
                            ch.pipeline().addLast(new HttpObjectAggregator(8192));
                            // 处理WebSocket握手以及处理控制帧
                            ch.pipeline().addLast(new WebSocketServerProtocolHandler("/ws"));

                            // 自定义Handler
                            ch.pipeline().addLast(new WebSocketMessageHandler());
                        }
                    });

            // 绑定端口，设置为同步，并且启动服务器
            ChannelFuture cf = bootstrap.bind(5566).sync();
            // 监听关闭通道
            cf.channel().closeFuture().sync();
        } finally {
            // 优雅的关闭
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }

    }

}
